
SARFFIX2_STARTUPCMDS = {"/startup", "/sf2startup", "/sarffix2startup"};

function SarfFix2:Startup_OnUpdate()
	local setup = SarfFix2.setup.startup;
	if ( setup.startupTime ) then
		local curTime = GetTime();
		if ( curTime - setup.startupTime > 30 ) then
			setup.startupTime = nil;
			SarfFix2:Startup_Execute();
			setup.frame:Hide();
		end
	end
	
end

function SarfFix2:Startup_Command(str)
	-- TODO: add, list, clear, remove, pop up big editbox (riiiiight!)
	SarfFix2:Startup_SetStartup(str);
end

function SarfFix2:Startup_PerformStartup()

	local setup = SarfFix2.setup.startup;
	if ( type(setup) ~= "table" ) then
		setup = {};
		SarfFix2.setup.startup = setup;
	end

	SarfFix2:RegisterSlashCmd(SARFFIX2_STARTUPCMDS, function(str) SarfFix2:Startup_Command(str) end, "STARTUPCMDS");
	
	if ( not setup.frame ) then
		local frame = CreateFrame("Frame", "SarfFix2_StartupFrame");
		setup.frame = frame;
		setup.startupTime = GetTime();
		frame:SetScript("OnUpdate", function() SarfFix2:Startup_OnUpdate(); end);
	end
	setup.frame:Show();
end
	
function SarfFix2:Startup_Execute()
	local realm = GetRealmName();
	local name = UnitName("player");
	local index = realm..":"..name;
	local startupData = SarfFix2:GetSetting("StartupData");
	if ( type(startupData) == "table" ) then
		local myScript = startupData[index];
		if ( myScript ~= nil ) then
			local func, errorMsg = loadstring(myScript,"SarfFix2 Startup");
			if ( func ~= nil ) then
				func();
			else
				SarfFix2:PrintError("SarfFix2 Startup: "..errorMsg);
			end
		end
	end
end

function SarfFix2:Startup_SetStartup(newData)
	local realm = GetRealmName();
	local name = UnitName("player");
	local index = realm..":"..name;
	local startupData = SarfFix2:GetSetting("StartupData");
	if ( type(startupData) ~= "table" ) then
		startupData = {};
	end
	startupData[index] = newData;
	SarfFix2:SetSetting("StartupData", startupData);
end

SarfFix2:AddInitializer(SarfFix2.Startup_PerformStartup);

